package com.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.reggie.dto.DishDto;
import com.reggie.entity.Dish;
import com.reggie.entity.DishFlavor;
import com.reggie.mapper.DishMapper;
import com.reggie.service.DishFlavorService;
import com.reggie.service.DishService;
import com.reggie.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {
    @Autowired
    private DishFlavorService dishFlavorService;


    @Transactional//事务绑定 保证菜品保存和口味保存一批执行成功或者失败
    public void saveWithFlavor(DishDto dishDto) {
        //1.保存菜品基本信息 ;
        this.save(dishDto);//dishService.save(dishDto);
        //2.获取保存的菜品ID ;
        Long dishId = dishDto.getId();
        //3.获取菜品口味列表，遍历列表，为菜品口味对象属性dishId赋值;
        List<DishFlavor> flavors = dishDto.getFlavors();
        flavors.forEach(item->item.setDishId(dishId));

        //保存菜品口味数据到菜品口味表dish_flavor
        dishFlavorService.saveBatch(flavors);
    }

    @Transactional
    public void updateSaveDish(DishDto dishDto) {
        //把dishDto都存在数据库里
        //菜品存储
        this.updateById(dishDto);
        Long dishId = dishDto.getId();
        //清理当前菜品对应口味数据---dish_flavor表的delete操作
        //不然更新不了新的 说已经存在了 她存的是一整个集合 不是单独分开
        //要更新整体都更新
        LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(DishFlavor::getDishId,dishDto.getId());
        dishFlavorService.remove(queryWrapper);
        //口味存储
        List<DishFlavor> flavors = dishDto.getFlavors();
        flavors.forEach(dishFlavor -> dishFlavor.setDishId(dishId));
        dishFlavorService.saveBatch(flavors);
    }
}
